<template>
  <div class="activity-charge-wrap">
    <el-form
      ref="form"
      label-position="top"
      :model="formData"
      :rules="rules"
      :disabled="$route.query.type === 'view'"
      scroll-to-error>
      <div
        class="page-box"
        style="margin-top: 0">
        <div class="box-head">基本信息</div>
        <field-cols
          :row-props="{ gutter: 24, align: 'bottom' }"
          :data="formData"
          :fields="fields">
          <template #title>
            <el-input
              v-model="formData.title"
              type="textarea"
              rows="5"
              placeholder="请输入新闻标题" />
          </template>
          <template #category>
            <el-select v-model="formData.category">
              <el-option
                v-for="(item, index) in opts.categoryList"
                :key="index"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </template>
          <template #alt>
            <el-input
              v-model="formData.alt"
              type="textarea"
              rows="5"
              placeholder="请输入新闻简述" />
          </template>
          <template #content>
            <div ref="editor"></div>
          </template>
          <template #imageUrl>
            <el-upload
              ref="uploadImg"
              :auto-upload="false"
              :show-file-list="false"
              list-type="picture-card"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="uploadImage">
              <img
                v-if="formData.imageUrl"
                :src="formData.imageUrl"
                class="avatar" />
              <el-icon
                v-else
                class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </template>
          <template #url>
            <el-input
              v-model="formData.url"
              placeholder="请输入新闻链接">
              <template #prepend>
                <el-select
                  v-model="formData.urlType"
                  style="width: 100px">
                  <el-option
                    v-for="(item, index) in opts.newUrlList"
                    :key="index"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </template>
            </el-input>
          </template>
        </field-cols>
      </div>
    </el-form>
    <div style="height: 24px"></div>
    <div class="edit-footer">
      <template v-if="$route.query.type == 'save'">
        <el-button @click="$router.go(-1)">返回</el-button>
        <promise-btn
          type="primary"
          @click="onSave">
          保存
        </promise-btn>
      </template>
      <el-button
        v-else
        @click="$router.go(-1)">
        返 回
      </el-button>
    </div>
  </div>
</template>
<script lang="ts">
import httpService from '@/utils/httpService';
import { newsManageAPI } from '@/config/api';

import { ElMessage, genFileId } from 'element-plus';
import type { UploadRawFile } from 'element-plus';
import Quill from 'quill';
import 'quill/dist/quill.snow.css'; // 引入样式

import { NewsCategory, NewsUrlCategory } from '@/constants/news';

export default {
  name: 'newsDetail',
  mixins: [],
  data() {
    return {
      id: this.$route.query.id,
      type: this.$route.query.type, // 0:查看,1:编辑
      formData: {
        author: '',
        title: '',
        category: '',
        alt: '',
        content: '',
        url: '',
        urlType: 0,
        imageUrl: '',
      },
      fields: [
        {
          name: 'author',
          label: '新闻作者',
          placeholder: '',
          colProps: { xs: 12, sm: 12, md: 12 },
        },
        {
          name: 'category',
          label: '新闻分类',
          placeholder: '',
          colProps: { xs: 12, sm: 12, md: 12 },
        },
        {
          name: 'title',
          label: '新闻标题',
          placeholder: '',
          colProps: { xs: 24, sm: 24, md: 24 },
        },
        {
          name: 'alt',
          label: '新闻简述',
          placeholder: '',
          colProps: { xs: 24, sm: 24, md: 24 },
        },
        {
          name: 'content',
          label: '新闻内容',
          placeholder: '',
          colProps: { xs: 24, sm: 24, md: 24 },
        },
        {
          name: 'url',
          label: '新闻链接',
          placeholder: '',
          colProps: { xs: 24, sm: 24, md: 24 },
        },
        {
          name: 'imageUrl',
          label: '新闻封面',
          placeholder: '',
          colProps: { xs: 24, sm: 24, md: 24 },
        },
      ],
      rules: {
        title: [{ required: true, message: '请输入新闻标题' }],
        category: [{ required: true, message: '请选择新闻分类' }],
        alt: [{ required: true, message: '请输入新闻简述' }],
      },
      editorData: null,
      opts: {
        categoryList: NewsCategory,
        newUrlList: NewsUrlCategory,
      },
    };
  },
  created() {
    if (this.id) this.getDetail();
  },
  mounted() {
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], // toggled buttons
      ['blockquote', 'code-block'],
      ['link', 'image', 'video', 'formula'],

      [{ header: 1 }, { header: 2 }], // custom button values
      [{ list: 'ordered' }, { list: 'bullet' }, { list: 'check' }],
      [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
      [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
      [{ direction: 'rtl' }], // text direction

      [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
      [{ header: [1, 2, 3, 4, 5, 6, false] }],

      [{ color: [] }, { background: [] }], // dropdown with defaults from theme
      [{ font: [] }],
      [{ align: [] }],

      ['clean'],
    ];
    this.editorData = new Quill(this.$refs.editor, {
      theme: 'snow', // 或者 'bubble'
      modules: {
        toolbar: toolbarOptions,
      },
      placeholder: '请输入新闻内容',
      theme: 'snow',
    });
  },
  methods: {
    // 新增/编辑新闻
    onSave() {
      this.$refs.form.validate(async flag => {
        if (!flag) return;
        let newsContent = this.editorData.root.innerHTML;
        newsContent = newsContent == '<p><br></p>' ? '' : newsContent;
        console.log('富文本内容:::', newsContent);
        const { code, data, message } = await httpService.post(
          this.id ? newsManageAPI.update : newsManageAPI.save,
          {
            ...this.formData,
            content: newsContent,
            id: this.id,
          },
          { showLoading: true },
        );
        if (code == 200) {
          ElMessage({
            message,
            type: 'success',
          });
          this.$router.go(-1);
        } else {
          ElMessage.error(message || '系统异常，请稍后重试');
        }
      });
    },
    // 新闻详情
    async getDetail() {
      const { code, data, message } = await httpService.get(
        newsManageAPI.getDetail,
        {
          id: this.id,
        },
        { showLoading: true },
      );
      if (code == '200') {
        this.formData = {
          author: data.author || '',
          title: data.title,
          category: data.category,
          alt: data.alt || '',
          content: data.content,
          url: data.url || '',
          urlType: data.urlType || 0,
          imageName: data.imageName || '',
          imageUrl: data.imageUrl || '',
        };
        this.editorData.root.innerHTML = data.content;
      } else {
        ElMessage.error(message);
      }
    },
    async uploadImage(imgData) {
      const { code, data, message } = await httpService.upload(
        newsManageAPI.upload,
        {
          file: imgData.raw,
        },
        { showLoading: true },
      );
      if (code == 200) {
        this.formData.imageName = imgData.name;
        this.formData.imageUrl = data;
      } else {
        ElMessage.error(message);
      }
    },
    handleExceed(files) {
      this.$refs.uploadImg?.clearFiles();
      const file = files[0] as UploadRawFile;
      file.uid = genFileId();
      this.$refs.uploadImg?.handleStart(file);
    },
  },
};
</script>
<style lang="scss" scoped>
img.avatar {
  width: 100%;
}
</style>
